<!-- 商品详情 -->
<template>
    <div>
        <app-head></app-head>
        <app-body>
            <div class="idle-details-container">
                <div class="details-header">
                    <div class="details-header-user-info">
                        <el-image
                            style="width: 80px; height: 80px; border-radius: 5px;"
                            :src="$store.state.baseApi + idleItemInfo.user.avatar"
                            fit="contain"></el-image>
                        <div style="margin-left: 10px;">
                            <div class="details-header-user-info-nickname"> 发布者：{{ idleItemInfo.user.nickname }}</div>
                            <div class="details-header-user-info-time"> 于{{ idleItemInfo.user.signInTime.substring(0, 10) }}加入平台</div>
                        </div>
                    </div>
                    <div class="details-header-buy">
                        <div class="price-section">
                            <div class="price">￥{{ totalPrice }}</div>
                            <div class="remaining">剩余 {{ idleItemInfo.idleNum }}</div>
                        </div>
                        <div class="quantity-section" v-if="!isMaster">
                            <el-button type="primary" plain @click="decreaseQuantity">-</el-button>
                            <el-input v-model="buyQuantity" type="number" min="1" class="quantity-input"></el-input>
                            <el-button type="primary" plain @click="increaseQuantity">+</el-button>
                        </div>
                        <div class="action-buttons">
                            <el-button v-if="!isMaster && idleItemInfo.idleStatus === 1" type="danger" plain @click="buyButton(idleItemInfo)" class="action-button">
                                立即购买
                            </el-button>
                            <el-button v-if="!isMaster && idleItemInfo.idleStatus === 1" type="primary" plain @click="favoriteButton(idleItemInfo)" class="action-button">
                                {{ isFavorite ? '撤出购物车' : '加入购物车' }}
                            </el-button>
                            <el-button v-if="isMaster && idleItemInfo.idleStatus === 1" type="danger" @click="changeStatus(idleItemInfo, 2)" plain>下架</el-button>
                            <el-button v-if="isMaster && idleItemInfo.idleStatus === 2" type="primary" @click="changeStatus(idleItemInfo, 1)" plain>重新上架</el-button>
                        </div>
                    </div>
                </div>

                <div class="details-info">
                    <div class="details-info-title">{{idleItemInfo.idleName}}</div>
                    <div class="details-info-main" v-html="idleItemInfo.idleDetails">
                    </div>
                    <div class="details-picture">
                        <el-image v-for="(imgUrl,i) in idleItemInfo.pictureList" :key="i"
                                  style="width: 90%;margin-bottom: 2px;"
                                  :src="$store.state.baseApi + imgUrl"
                                  fit="contain"></el-image>
                    </div>
                </div>

                <div class="message-container" id="replyMessageLocation">
                    <div class="message-title">全部留言</div>
                    <div class="message-send">
                        <div v-if="isReply" style="padding-bottom: 10px;">
                            <el-button type="info" @click="cancelReply">回复：{{replyData.toMessage}} @{{replyData.toUserNickname}} <i class="el-icon-close el-icon--right"></i></el-button>
                        </div>
                        <el-input
                                type="textarea"
                                autosize
                                placeholder="留言提问..."
                                v-model="messageContent"
                                maxlength="200"
                                show-word-limit>
                        </el-input>
                        <div class="message-send-button">
                            <el-button @click="sendMessage" type="success"> 发送留言</el-button>
                        </div>
                    </div>
                    <div>
                        <div v-for="(mes,index) in messageList" :key="index" class="message-container-list">
                            <div class="message-container-list-left">
                                <el-image
                                        style="width: 55px; height: 55px;border-radius: 5px;"
                                        :src="$store.state.baseApi + mes.fromU.avatar"
                                        fit="contain"></el-image>
                                <div class="message-container-list-text">
                                    <div class="message-nickname">{{mes.fromU.nickname}}
                                        {{mes.toU.nickname?' @'+mes.toU.nickname+'：'+
                                        mes.toM.content.substring(0,10)+
                                        (mes.toM.content.length>10?'...':''):''}}</div>
                                    <div class="message-content">{{mes.content}}</div>
                                    <div class="message-time">{{mes.createTime}}</div>
                                </div>
                            </div>
                            <div class="message-container-list-right">
                                <el-button style="float: right;"  plain @click="replyMessage(index)"> 回复</el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <app-foot></app-foot>
        </app-body>
    </div>
</template>

<script>
    import AppHead from '../common/AppMeHeader.vue';
    import AppBody from '../common/AppPageBody.vue'
    import AppFoot from '../common/AppFoot.vue'

    export default {
        name: "idle-details",
        components: {
            AppHead,
            AppBody,
            AppFoot
        },
        watch: {
            buyQuantity(value) {
              // 如果购买数量大于剩余数量
              if (value > this.idleItemInfo.idleNum) {
                // 将购买数量设置为剩余数量
                this.buyQuantity = this.idleItemInfo.idleNum;
                // 显示错误消息提示购买数量不能超过剩余数量
                this.$message.error('购买数量不能超过剩余数量');
              // 如果购买数量小于1
              } else if (value < 1) {
                // 将购买数量设置为1
                this.buyQuantity = 1;
              }
              // 更新总价
              this.updateTotalPrice();
            }
        },
        data() {
            return {
                messageContent:'',
                toUser:null,
                toMessage:null,
                isReply:false,
                replyData:{
                    toUserNickname:'',
                    toMessage:''
                },
                messageList:[],
                idleItemInfo:{
                    id:'',
                    idleName:'',
                    idleDetails:'',
                    pictureList:[],
                    idlePrice:0,
                    idlePlace:'',
                    idleLabel:'',
                    idleStatus:-1,
                    userId:'',
                    user:{
                        avatar:'',
                        nickname:'',
                        signInTime:''
                    },
                    idleNum:""
                },
                isMaster:false,
                isFavorite:true,
                favoriteId:0,
                buyQuantity: 1,
                totalPrice: 0,
            };
        },
        /**
         * 组件挂载完成后执行的方法
         */
        mounted(){
            // 从路由中获取 id 参数
            let id=this.$route.query.id;
            // 调用 API 获取物品信息
            this.$api.getIdleItem({
                id:id
            }).then(res=>{
                // 输出返回结果
                console.log(res);
                if(res.data){
                    // 将闲置物品详情按换行符分割成数组
                    let list=res.data.idleDetails.split(/\r?\n/);
                    let str='';
                    // 将数组中的每一项转换为 HTML 段落标签并拼接
                    for(let i=0;i<list.length;i++){
                        str+='<p>'+list[i]+'</p>';
                    }
                    // 将拼接后的 HTML 字符串赋值回闲置物品详情
                    res.data.idleDetails=str;
                    // 将图片列表字符串解析为 JSON 对象
                    res.data.pictureList=JSON.parse(res.data.pictureList);
                    // 将处理后的闲置物品信息赋值给组件的 data 属性
                    this.idleItemInfo=res.data;
                    this.totalPrice = this.idleItemInfo.idlePrice;
                    // 从 Cookie 中获取用户 ID
                    let userId=this.getCookie('shUserId');
                    // 判断当前用户是否为物品的发布者
                    if(userId == this.idleItemInfo.userId){
                        console.log('isMaster');
                        // 设置 isMaster 为 true，表示当前用户为发布者
                        this.isMaster=true;
                    }

                    // 调用 checkFavorite 方法
                    this.checkFavorite();
                    // 调用 getAllIdleMessage 方法
                    this.getAllIdleMessage();
                }
                // 页面滚动到顶部
                $('html,body').animate({
                    scrollTop: 0
                }, {duration: 500, easing: "swing"});
            });
        },
        methods: {
            increaseQuantity() {
                if (this.buyQuantity < this.idleItemInfo.idleNum) {
                    this.buyQuantity++;
                } else {
                    this.$message.error('购买数量不能超过剩余数量');
                }
                this.updateTotalPrice();
                },
                decreaseQuantity() {
                if (this.buyQuantity > 1) {
                    this.buyQuantity--;
                }
                this.updateTotalPrice();
                },
                updateTotalPrice() {
                this.totalPrice = this.buyQuantity * this.idleItemInfo.idlePrice;
                },
            getAllIdleMessage(){
                this.$api.getAllIdleMessage({
                    idleId:this.idleItemInfo.id
                }).then(res=>{
                    console.log('getAllIdleMessage',res.data);
                    if(res.status_code===1){
                        this.messageList=res.data;
                    }
                }).catch(()=>{
                })
            },
            /**
             * 检查是否收藏
             *
             * @returns 无返回值，但会更新组件中的isFavorite和favoriteId属性
             */
            checkFavorite(){
                this.$api.checkFavorite({
                    idleId:this.idleItemInfo.id
                }).then(res=>{
                    if(!res.data){
                        this.isFavorite=false;
                    }else {
                        this.favoriteId=res.data;
                    }
                })
            },
            /**
             * 获取指定名称的cookie值
             *
             * @param cname cookie名称
             * @returns 返回指定名称的cookie值，如果未找到则返回空字符串
             */
            getCookie(cname){
                var name = cname + "=";
                var ca = document.cookie.split(';');
                for(var i=0; i<ca.length; i++)
                {
                    var c = ca[i].trim();
                    if (c.indexOf(name)===0) return c.substring(name.length,c.length);
                }
                return "";
            },
            /**
             * 回复消息
             *
             * @param index 消息在messageList数组中的索引
             * @description
             * 将页面滚动到回复消息位置，并设置回复数据
             * 回复数据包括：回复对象昵称、回复内容、接收消息用户ID、消息ID
             */
            replyMessage(index){
                $('html,body').animate({
                    scrollTop: $("#replyMessageLocation").offset().top-600
                }, {duration: 500, easing: "swing"});
                this.isReply=true;
                this.replyData.toUserNickname=this.messageList[index].fromU.nickname;
                this.replyData.toMessage=this.messageList[index].content.substring(0,10)+(this.messageList[index].content.length>10?'...':'');
                this.toUser=this.messageList[index].userId;
                this.toMessage=this.messageList[index].id;
            },
            /**
             * 修改空闲物品状态
             *
             * @param idle 空闲物品对象
             * @param status 状态值
             * @returns 无返回值
             */
            changeStatus(idle,status){
                this.$api.updateIdleItem({
                    id:idle.id,
                    idleStatus:status
                }).then(res=>{
                    console.log(res);
                    if(res.status_code===1){
                        this.idleItemInfo.idleStatus=status;
                    }else {
                        this.$message.error(res.msg)
                    }
                });
            },
            /**
             * 购买按钮函数
             *
             * @param idleItemInfo 闲置物品信息
             * @param idleItemInfo.id 闲置物品ID
             * @param idleItemInfo.idlePrice 闲置物品价格
             * @returns 无返回值
             */
            buyButton(idleItemInfo){
                if (this.buyQuantity > this.idleItemInfo.idleNum) {
                    this.$message.error('购买数量不能超过剩余数量');
                } else {
                    this.$api.addOrder({
                        idleId: idleItemInfo.id,
                        orderPrice: this.totalPrice,
                        orderNum: this.buyQuantity,
                }).then(res=>{
                    console.log(res);
                    if(res.status_code===1){
                        this.$router.push({path: '/order', query: {id: res.data.id}});
                    }else {
                        this.$message.error(res.msg)
                    }
                }).catch(e=>{

                })
                }
            },
            /**
             * 购物车按钮的点击事件
             *
             * @param idleItemInfo 闲置物品信息
             * @returns 无返回值
             */
            favoriteButton(idleItemInfo){
                if(this.isFavorite){
                    this.$api.deleteFavorite({
                        id: this.favoriteId
                    }).then(res=>{
                        console.log(res);
                        if(res.status_code===1){
                            this.$message({
                                message: '已撤出购物车！',
                                type: 'success'
                            });
                            this.isFavorite=false;
                        }else {
                            this.$message.error(res.msg)
                        }
                    }).catch(e=>{
                    })
                }else {
                    this.$api.addFavorite({
                        idleId:idleItemInfo.id
                    }).then(res=>{
                        console.log(res);
                        if(res.status_code===1){
                            this.$message({
                                message: '已加入购物车！',
                                type: 'success'
                            });
                            this.isFavorite=true;
                            this.favoriteId=res.data;
                        }else {
                            this.$message.error(res.msg)
                        }
                    }).catch(e=>{
                    })
                }
            },
            /**
             * 取消回复
             *
             * @description 将回复状态设为未回复，重置回复数据
             */
            cancelReply(){
                this.isReply=false;
                this.toUser=this.idleItemInfo.userId;
                this.toMessage=null;
                this.replyData.toUserNickname='';
                this.replyData.toMessage='';
            },
            /**
             * 发送消息
             *
             * @returns 无返回值
             */
            sendMessage(){
                let content=this.messageContent.trim();
                if(this.toUser==null){
                    this.toUser=this.idleItemInfo.userId;
                }
                if(content){
                    let contentList=content.split(/\r?\n/);
                    let contenHtml=contentList[0];
                    for(let i=1;i<contentList.length;i++){
                        contenHtml+='<br>'+contentList[i];
                    }
                    this.$api.sendMessage({
                        idleId:this.idleItemInfo.id,
                        content:contenHtml,
                        toUser:this.toUser,
                        toMessage:this.toMessage
                    }).then(res=>{
                        if(res.status_code===1){
                            this.$message({
                                message: '留言成功！',
                                type: 'success'
                            });
                            this.messageContent='';
                            this.cancelReply();
                            this.getAllIdleMessage();
                        }else {
                            this.$message.error("留言失败！"+res.msg);
                        }
                    }).catch(()=>{
                        this.$message.error("留言失败！");
                    });

                }else{
                    this.$message.error("留言为空！");
                }
            }
        },
    }
</script>

<style scoped>
    .idle-details-container {
        min-height: 85vh;
    }

    .details-header {
        height: 80px;
        border-bottom: 10px solid #f6f6f6;
        display: flex;
        justify-content: space-between;
        padding: 20px;
        align-items: center;
    }

    .details-header-user-info {
        display: flex;
    }

    .details-header-user-info-nickname {
        font-size: 22px;
        margin-bottom: 10px;
    }

    .details-header-user-info-time {
        font-size: 16px;
        color: #555555;
    }

    .details-header-buy {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        gap: 20px;
    }

    .price-section {
        text-align: right;
        margin-right: 20px;
    }

    .price {
        color: red;
        font-size: 32px;
        font-weight: 600;
    }

    .remaining {
        font-size: 13px;
        margin-bottom: 10px;
    }

    .quantity-section {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .quantity-input {
        width: 80px;
        text-align: center;
    }

    .action-buttons {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        gap: 10px;
    }

    .details-info {
        padding: 20px 50px;
    }

    .details-info-title {
        font-size: 22px;
        font-weight: 600;
        margin-bottom: 20px;

    }

    .details-info-main {
        font-size: 17px;
        color: #121212;
        line-height: 160%;
    }

    .details-picture {
        margin: 20px 0;
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    .message-container {
        min-height: 100px;
        border-top: 10px solid #f6f6f6;
        padding: 20px;
    }
    .action-button {
        width: auto; /* 或者设置具体的宽度值 */
        height: auto; /* 或者设置具体的高度值 */
        font-size: inherit; /* 继承父元素的字体大小 */
        /* 其他按钮样式 */
    }
    .message-title {
        font-size: 20px;
        font-weight: 600;
        margin-bottom: 20px;
    }
    .message-send{
        min-height: 60px;
    }
    .message-send-button{
        margin-top: 10px;
        display: flex;
        justify-content: flex-end;
    }
    .message-container-list{
        min-height: 60px;
        border-top: 1px solid #eeeeee;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15px 0;
    }
    .message-container-list:first-child{
        border-top:none;
    }
    .message-container-list-left{
        width: 850px;
        display: flex;
    }
    .message-container-list-right{
        width: 100px;
    }
    .message-container-list-text{
        margin-left: 10px;
    }
    .message-nickname{
        font-weight: 600;
        font-size: 18px;
        padding-bottom: 5px;
    }
    .message-content{
        font-size: 16px;
        padding-bottom: 15px;
        color: #555555;
        width: 770px;
    }
    .message-time{
        font-size: 13px;
        color: #555555;
    }
</style>